var express = require('express');
var router = express.Router();

const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')

router.get('/list', (req, res, next) => {
    // express 的 req.query 是原生自带的，不用手动解析
    let author = req.query.author || ''
    const keyword = req.query.keyword || ''

    // 修改登录权限
    if (req.query.isadmin) {
        // 管理员界面
        if (req.session.username == null) {
            // 未登录情况
            res.json(
                new ErrorModel('未登录')
            )
            
            return
        }
        // 强制查询自己的博客
        author = req.session.username
    }

    const result = getList(author, keyword)
    return result.then(listData => {
        // 不用 return
        res.json(
            new SuccessModel(listData)
        )
    })
})

router.get('/detail', (req, res, next) => {
    const result = getDetail(req.query.id)
    return result.then(listData => {
        res.json(
            new SuccessModel(listData)
        )
     })
})

router.post('/new', loginCheck, (req, res, next) => {
    req.body.author = req.session.username
    const result = newBlog(req.body)
    // 这里的 data 就是返回新建成功的博客的 id
    return result.then(data => {
        res.json(
            new SuccessModel(data)
        )
    })
})

router.post('/update', loginCheck, (req, res, next) => {
    req.body.author = req.session.username
    const result = updateBlog(req.query.id, req.body)

    return result.then(data => {
        if (data) {
            res.json(
                new SuccessModel()
            )
            return
        }

        res.json(
            new ErrorModel('update failed')
        )
    })
})

router.post('/del', loginCheck, (req, res, next) => {
    const author = req.session.username
    const result = deleteBlog(req.query.id, author)

    return result.then(data => {
        if (data) {
            res.json(
                new SuccessModel()
            )
            return
        }

        res.json(
            new ErrorModel('update failed')
        )
    })
})

module.exports = router;